package com.chejianer.phone.utils;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * Created by Chejianer on 2016/8/31.
 */
public class ExcelUtils {
    public static void excelOut(HttpServletResponse response,ArrayList arrayList, String[] headers){
        WritableWorkbook book=null;
        OutputStream os=null;
        try {
            //获取输出流
            os=response.getOutputStream();
            //清空输出流
            response.reset();
            //设定输出文件头
            response.setHeader("Content-disposition","attachment;filename="+new String("呵呵哒".getBytes("GB2312"),"8859_1")+".xls");
            //定义输出类型
            response.setContentType("application/msexcel");
            //建立excel文件
           book= Workbook.createWorkbook(os);
            //创建一个工作表
            WritableSheet sheet=book.createSheet("sheet",0);
            //先把标题写好
            //String[] headers={"学号","姓名","性别"};
            outExcelHeaders(headers,sheet);
            for(int i=0;i<arrayList.size();i++){
                //获取类对象
                Object ob=arrayList.get(i);
                Class cl=ob.getClass();
                Field[] f=cl.getDeclaredFields();
                for(int j=0;j<f.length;j++){
                    //获得读写权限
                    f[j].setAccessible(true);
                    Label label=new Label(j,i+1,String.valueOf(f[j].get(ob)));
                    sheet.addCell(label);
                }
            }
            //写入
            book.write();
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置表头信息,利用poi
     * @param headersInfo
     * @param sheet
     */
    public static void outputHeaders(String[] headersInfo,HSSFSheet sheet ){
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headersInfo.length; i++) {
            sheet.setColumnWidth(i, 4000);
            row.createCell(i).setCellValue(headersInfo[i]);
        }
    }

    /**
     * 设置表头信息，利用jxl
     * @param headersInfo 表头信息数组
     * @param sheet 表
     * @throws WriteException
     */
    public static void outExcelHeaders(String[] headersInfo,WritableSheet sheet) throws WriteException {
        //设置字体样式
        WritableFont font=new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.RED);
        WritableCellFormat cellFormat=new WritableCellFormat(font);
        for(int i=0;i<headersInfo.length;i++){
            Label label=new Label(i,0,headersInfo[i],cellFormat);
                sheet.addCell(label);

        }
    }


}
